package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.*;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.*;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_UP_KEY;

/**
 * @author 虎哥
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuDetailService detailService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpecParamService paramService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public PageDTO<SpuDTO> querySpuByPage(
            Integer page, Integer rows, Boolean saleable, Long categoryId, Long brandId, Long id) {
        // 1.分页信息的健壮性处理
        if (page < 0 || rows < 0) {
            throw new LyException(400, "分页参数错误");
        }
        // 2.查询 SELECT s.* FROM tb_spu s
        Page<Spu> result = query()
                //WHERE  //   s.id = 1
                .eq(id != null, "id", id)
                //  AND s.cid3 = 105
                .eq(categoryId != null, "cid3", categoryId)
                //  AND s.brand_id = 18374
                .eq(brandId != null, "brand_id", brandId)
                //  AND s.saleable = 1
                .eq(saleable != null, "saleable", saleable)
                //LIMIT 0, 5
                .page(new Page<>(page, rows));

        // 3.转换DTO
        List<SpuDTO> dtoList = SpuDTO.convertEntityList(result.getRecords());

        // 4.处理分类和品牌名称
        for (SpuDTO spuDTO : dtoList) {
            handleCategoryAndBrandName(spuDTO);
        }
        // 5.封装返回
        return new PageDTO<>(result.getTotal(), result.getPages(), dtoList);
    }

    @Override
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        // 1.新增SPU
        // 1.1.转换PO
        Spu spu = spuDTO.toEntity(Spu.class);
        // 1.2.默认是下架
        spu.setSaleable(false);
        // 1.3.新增
        boolean success = save(spu);
        if (!success) {
            throw new LyException(500, "新增商品失败！");
        }
        // 1.4.ID回显
        Long spuId = spu.getId();

        // 2.新增SpuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        // 2.1.转换PO
        SpuDetail spuDetail = spuDetailDTO.toEntity(SpuDetail.class);
        // 2.2.填id
        spuDetail.setSpuId(spuId);
        // 2.3.新增
        success = detailService.save(spuDetail);
        if (!success) {
            throw new LyException(500, "新增商品失败！");
        }

        // 3.新增SKU
        List<SkuDTO> skus = spuDTO.getSkus();
        // 3.1.转换PO
        List<Sku> skuList = skus.stream().map(skuDTO -> {
            Sku sku = skuDTO.toEntity(Sku.class);
            sku.setSpuId(spuId);
            sku.setSold(0L);
            sku.setSaleable(false);
            return sku;
        }).collect(Collectors.toList());
        // 3.2.新增
        skuService.saveBatch(skuList);
    }

    @Override
    @Transactional
    public void updateSaleable(Long spuId, Boolean saleable) {
        // 更新商品的上下架字段。UPDATE tb_spu p SET p.saleable = 1 WHERE p.id = 1
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(saleable);
        boolean success = updateById(spu);
        if (!success) {
            throw new LyException(500, "更新上下架失败");
        }
        // 2.更新sku的上下架字段
        // UPDATE tb_sku p SET p.saleable = 1 WHERE p.spu_id = 1
        success = skuService.update().set("saleable", saleable).eq("spu_id", spuId).update();
        if (!success) {
            throw new LyException(500, "更新上下架失败");
        }

        // 发送MQ消息
        String routingKey = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME, routingKey, spuId);
    }

    @Override
    public SpuDTO queryGoodsById(Long spuId) {
        // 1.查询spu
        Spu spu = getById(spuId);
        // 1.1.转换DTO
        SpuDTO spuDTO = new SpuDTO(spu);
        // 1.2.分类和品牌名称
        handleCategoryAndBrandName(spuDTO);

        // 2.查询spuDetail
        spuDTO.setSpuDetail(detailService.queryDetailBySpuId(spuId));

        // 3.查询sku
        spuDTO.setSkus(skuService.querySkuBySpuId(spuId));

        return spuDTO;
    }

    @Override
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        // 1.修改SPU
        if (spuDTO.getId() != null) {
            // 1.1.spu数据需要修改，转换为PO
            Spu spu = spuDTO.toEntity(Spu.class);
            // 1.2.禁止修改saleable
            spu.setSaleable(null);
            // 1.3.更新
            boolean success = updateById(spu);
            if (!success) {
                throw new LyException(500, "更新商品失败！");
            }
        }
        // 2.修改SpuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        if (spuDetailDTO != null && spuDetailDTO.getSpuId() != null) {
            // 2.1.需要更新detail，转换PO
            SpuDetail detail = spuDetailDTO.toEntity(SpuDetail.class);
            // 2.2.更新
            boolean success = detailService.updateById(detail);
            if (!success) {
                throw new LyException(500, "更新商品失败！");
            }
        }
        // 3.修改SKU
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        // 3.1.判断是否存在
        if (CollectionUtils.isEmpty(skuDTOList)) {
            // 没有sku，无需处理
            return;
        }
        // 3.2.需要增删改，
        Map<Boolean, List<Sku>> skuMap = skuDTOList.stream()
                // 先转为PO
                .map(skuDTO -> skuDTO.toEntity(Sku.class))
                // 继续判断，对集合分组，分组的依据是是否包含saleable，包含：则要删除，不包含：则增或改
                .collect(Collectors.groupingBy(sku -> sku.getSaleable() != null));
        // 3.3.获取要删除的sku
        List<Sku> deleteSkuList = skuMap.get(true);
        if(!CollectionUtils.isEmpty(deleteSkuList)){
            // 需要删除，获取sku的id
            List<Long> deleteIdList = deleteSkuList.stream().map(Sku::getId).collect(Collectors.toList());
            // 批量删除
            skuService.removeByIds(deleteIdList);
        }
        // 3.4.获取要增改的sku
        List<Sku> insertOrUpdateSkuList = skuMap.get(false);
        if(!CollectionUtils.isEmpty(insertOrUpdateSkuList)) {
            // 批量新增或修改
            insertOrUpdateSkuList.forEach(sku -> sku.setSaleable(false));
            skuService.saveOrUpdateBatch(insertOrUpdateSkuList);
        }
    }

    @Override
    public List<SpecParamDTO> querySpecValues(Long spuId, Boolean searching) {
        // 1.查询spu
        Spu spu = getById(spuId);
        if (spu == null) {
            throw new LyException(404, "商品不存在！");
        }
        // 2.查询规格参数集合
        Long categoryId = spu.getCid3();
        // 2.1.查询规格参数
        List<SpecParamDTO> params = paramService.querySpecParams(categoryId, null, searching);

        // 3.查询规格参数值
        // 3.1.根据id查询detail
        SpuDetail detail = detailService.getById(spuId);
        // 3.2.取出规格参数json串
        String specJson = detail.getSpecification();
        // 3.3.把json串变为map，key是参数id，值是参数值
        Map<Long, Object> specValueMap = JsonUtils.toMap(specJson, Long.class, Object.class);

        // 4.参数值填到SpecParamDTO
        for (SpecParamDTO param : params) {
            Object value = specValueMap.get(param.getId());
            param.setValue(value);
        }
        return params;
    }

    private void handleCategoryAndBrandName(SpuDTO spuDTO) {
        // 获取三级分类id
        List<Long> categoryIds = spuDTO.getCategoryIds();
        // 查询三级分类
        List<Category> categories = categoryService.listByIds(categoryIds);
        if (!CollectionUtils.isEmpty(categories)) {
            // 拼接分类名称
            String names = categories.stream().map(Category::getName).collect(Collectors.joining("/"));
            // 设置分类名称
            spuDTO.setCategoryName(names);
        }
        // 获取品牌id
        Long brandId = spuDTO.getBrandId();
        // 根据id查询品牌
        Brand brand = brandService.getById(brandId);
        if (brand != null) {
            // 设置品牌名称
            spuDTO.setBrandName(brand.getName());
        }
    }
}
